﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace WssUtils
{
    public class Timer
    {
        public enum State
        {
            Idle,
            Running,
            Finished
        }

        private State state = State.Idle;
        private State _lastState = State.Idle;

        public float duration = 1.0f;
        private float elapseTime = 0;
        private bool loop = false;
        public bool paused = false;

        public Timer(float duration = 0.5f, bool loop = false)
        {
            this.duration = duration;
            this.loop = loop;
        }

        public bool IsFinshed { get => state == State.Finished; }
        public bool IsRunning { get => state == State.Running; }
        public bool OnFinished { get; private set; }
        public float progress => Mathf.Clamp(elapseTime / duration, 0, 1);
        public float ElapseTime { get => elapseTime; set => elapseTime = value; }
        public float LeftTime { get => Mathf.Max(this.duration - elapseTime, 0); }

        public void StartTimer(float duration, bool loop = false)
        {
            if (duration <= 0) duration = 0.01f;
            this.loop = loop;
            this.duration = duration;
            state = State.Running;
            elapseTime = 0;
            OnFinished = false;
            paused = false;
        }

        /// <summary>
        /// 需要手动驱动 Tick() 运行
        /// </summary>
        public void Tick(float dt = -1)
        {
            if (paused) return;
            if (dt == -1) dt = Time.deltaTime;
            this.elapseTime += dt;
            switch (state)
            {
                case State.Idle:
                    break;
                case State.Running:
                    if (this.elapseTime >= this.duration)
                    {
                        this.state = State.Finished;
                    }
                    break;
                case State.Finished:
                    if (loop)
                    {
                        elapseTime = 0;
                        this.state = State.Running;
                    }
                    break;
            }

            OnFinished = false;
            if (state != _lastState)
            {
                _lastState = state;
                if (state == State.Finished)
                {
                    OnFinished = true;
                }


            }

        }


    }

}